﻿gbDebug = True;

try:
  import xbmc, xbmcgui;
except:
  # For command line testing outside of XBMC
  from FakeXBMC import FakeXBMC;
  from FakeXBMCGUI import FakeXBMCGUI;
  xbmc = FakeXBMC();
  xbmcgui = FakeXBMCGUI();

def askInformationAndSelectTitles(oSettings, oDisc):
  oDialog = xbmcgui.Dialog();
  if gbDebug:
    print "%s: Asking user for information about the disc..." % __file__;

  sName = " ".join([
      sWord[0].upper() + sWord[1:].lower()
      for sWord in oDisc.getInfo("name", "").replace("_", " ").split(" ")
  ]);

  oKeyboard = xbmc.Keyboard(sName, "Please enter the name of this disc:");
  oKeyboard.doModal();
  if not oKeyboard.isConfirmed():
    if gbDebug:
      print "%s: User cancelled name input." % __file__;
    return False;
  oDisc.sName = oKeyboard.getText();
  if gbDebug:
    print "%s: User said disc is named %s." % (__file__, repr(oDisc.sName));

  doTitles_by_iId = oDisc.getBranchesById();
  if oDisc.bIsMovie:
    sYear = str(oDisc.iYear);
    while 1:
      oKeyboard = xbmc.Keyboard(sYear, "Please enter the year of this movie:");
      oKeyboard.doModal();
      if not oKeyboard.isConfirmed():
        if gbDebug:
          print "%s: User cancelled year input." % __file__;
        return False;
      sYear = oKeyboard.getText();
      try:
        oDisc.iYear = int(sYear.strip());
      except ValueError:
        oDialog.ok(oSettings.sName, "Please enter a valid year, as in 4 digits.");
      else:
        break;
      #loop
    if gbDebug:
      print "%s: User said disc year is %d." % (__file__, oDisc.iYear);
    if len(doTitles_by_iId) == 1:
      if gbDebug:
        print "%s: Only one title: automatically selected %d." % (__file__, doTitles_by_iId.keys()[0]);
    else:
      if gbDebug:
        print "%s: Found %d movie titles, asking user which title to rip..." % (__file__, len(doTitles_by_iId));
      asTitleDescriptions = [oTitle.sDescription for oTitle in doTitles_by_iId.values()];
      iMainTitleId = oDialog.select("Select the movie from the following titles on disc:", asTitleDescriptions);
      if iMainTitleId is None:
        if gbDebug:
          print "%s: User pressed cancel." % __file__;
        return False;
      if gbDebug:
        print "%s: User selected movie title #%d." % (__file__, iMainTitleId);
      for iTitleId in doTitles_by_iId:
        if iTitleId != iMainTitleId:
          oDisc.removeBranch(iTitleId);
  else:
    sSeason = "";
    while 1:
      oKeyboard = xbmc.Keyboard(sSeason, "Please enter the season number of this disc or leave empty:");
      oKeyboard.doModal();
      sSeason = oKeyboard.getText();
      if not oKeyboard.isConfirmed():
        return False;
      if sSeason == "":
        oDisc.iSeason = None;
        if gbDebug:
          print "%s: User said TV show has no seasons." % __file__;
        break;
      else:
        try:
          oDisc.iSeason = int(sSeason.strip());
        except ValueError:
          oDialog.ok(oSettings.sName, "Please enter a valid number, as in one or more digits.", \
              "Or leave blank if the series has no seasons");
        else:
          if gbDebug:
            print "%s: User said disc's TV show season is %d." % (__file__, oDisc.iSeason);
          break;
    sFirstEpisodeNumber = "1";
    while 1:
      oKeyboard = xbmc.Keyboard(sFirstEpisodeNumber, "Please enter the number of the first episode on this disc:");
      oKeyboard.doModal();
      sFirstEpisodeNumber = oKeyboard.getText();
      if not oKeyboard.isConfirmed():
        return False;
      try:
        oDisc.iFirstEpisodeNumber = int(sFirstEpisodeNumber.strip());
      except ValueError:
        oDialog.ok(oSettings.sName, "Please enter a valid number, as in one or more digits.");
      else:
        if gbDebug:
          print "%s: User said disc's first episode number is %d." % (__file__, oDisc.iFirstEpisodeNumber);
        break;
    if len(doTitles_by_iId) > 2:
      if gbDebug:
        print "%s: Multiple series titles: checking for a combined title containing all the others..." % __file__;
      # Series will often have individual episodes as titles as well as all episodes as one continuous title.
      # Let's see if there is one title that is within 1% of the combined length of the others:
      iAllTitlesDuration = 0;
      iLongestTitleDuration = 0;
      iLongestTitleId = None;
      for iId, oTitle in doTitles_by_iId.items():
        sDuration = oTitle.getInfo("duration") or "0:0:0";
        sHours, sMinutes, sSeconds = sDuration.split(":");
        iDuration = (int(sHours) * 60 + int(sMinutes)) * 60 + int(sSeconds);
        if gbDebug:
          print "%s: Duration of title #%d is %ds" % (__file__, iId, iDuration);
        iAllTitlesDuration += iDuration;
        if iDuration > iLongestTitleDuration:
          iLongestTitleDuration = iDuration;
          iLongestTitleId = iId;
      nSizeDifferenceBetweenLongestAndOthers = abs(iLongestTitleDuration / float(iAllTitlesDuration) - 0.5);
      if nSizeDifferenceBetweenLongestAndOthers < 0.01:
        if gbDebug:
          print "%s: Found a \"combined\" title: #%d will not be ripped." % (__file__, iId);
        oDisc.removeBranch(iLongestTitleId);
        print "%s: %d TV show titles selected." % (__file__, len(doTitles_by_iId) - 1);
      else:
        print "%s: All %d TV show titles selected." % (__file__, len(doTitles_by_iId));
    elif len(doTitles_by_iId) == 2:
      if gbDebug:
        print "%s: All 2 TV show titles selected." % __file__;
    else:
      if gbDebug:
        print "%s: 1 TV show title selected." % __file__;
      
  return True;
